package com.smartcampusbackend.controller;

import com.smartcampusbackend.service.UserService;
import com.smartcampusbackend.mapper.SystemLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/stats")
public class StatsController {
    @Autowired
    private UserService userService;
    @Autowired
    private SystemLogMapper systemLogMapper;

    @GetMapping("/overview")
    public Map<String, Object> getOverview() {
        Map<String, Object> result = new HashMap<>();
        // 总用户数
        int totalUser = (int) userService.count();
        // 今日访问（登录数）
        long todayVisit = (long) systemLogMapper.getTodayStats().getOrDefault("loginCount", 0L);
        // 系统警告（今日错误日志数）
        long systemWarning = (long) systemLogMapper.getTodayStats().getOrDefault("errorCount", 0L);
        // 在线用户数（近10分钟有登录日志的用户数）
        String tenMinAgo = LocalDateTime.now().minusMinutes(10).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        long onlineUser = systemLogMapper.countRecentLoginUsers(tenMinAgo);

        result.put("totalUser", totalUser);
        result.put("onlineUser", (int) onlineUser);
        result.put("todayVisit", (int) todayVisit);
        result.put("systemWarning", (int) systemWarning);
        System.out.println("totalUser"+totalUser);
        System.out.println("onlineUser"+(int) onlineUser);
        System.out.println("todayVisit"+(int) todayVisit);
        System.out.println("systemWarning"+(int) systemWarning);
        return result;
    }
} 